import axios from 'axios'
import {
  sm4KeyGenerator,
  getRequestKey,
  encryptRequestData,
  getResponseJson
} from '@/utils/sm'

// sm4秘钥
const sm4Key = sm4KeyGenerator()
// 是否加密
const isAddSm = true
// sm4Key数组
const sm4KeyArr = []

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
  // 将秘钥加密后放到请求头中
  config.headers.RequestKey = getRequestKey(sm4Key, false) // 请求key
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?'
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName]
      const part = encodeURIComponent(propName) + '='
      if (value !== null && typeof (value) !== 'undefined') {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            url += subPart + encodeURIComponent(value[key]) + '&'
          }
        } else {
          url += part + encodeURIComponent(value) + '&'
        }
      }
    }
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  } else if (config.method === 'post') {
    if (isAddSm && config.url.indexOf('upload') === -1) {
      config.data = encryptRequestData(config.data, sm4Key, config.method)
      const obj = {}
      obj.url = config.url
      obj.sm4keyNum = sm4Key
      obj.cis_req_params = config.data.cis_req_params
      sm4KeyArr.push(obj)
    }
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200
  // 返回值解密
  if (isAddSm) {
    if (res.config.method !== 'OPTIONS') {
      let i
      let myKey
      if (res.config.method === 'post') {
        for (const item in sm4KeyArr) {
          if (sm4KeyArr[item].cis_req_params === JSON.parse(res.config.data).cis_req_params) {
            myKey = sm4KeyArr[item].sm4keyNum
            i = item
          }
        }
        if (code === 200) {
          res.data = getResponseJson(res.data, myKey)
        }
        sm4KeyArr.splice(i, 1)
      }
    } else {
      return
    }
  }
  if (code !== 200) {
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject('error')
  } else {
    return res.data
  }
},
error => {
  console.log('err' + error)
  return Promise.reject(error)
})

export default service
